import { showMessage } from '@/components/antd-comp/message'
import ModalComponent from '@/components/antd-comp/modal/ModalComponent'
import ThemeBtn from '@/components/antd-comp/theme-btn'
import { UploadIcon } from '@/components/bs-icons/upload'
import { useBuriedEvent } from '@/util/buried'
import type { UploadProps } from 'antd'
import { Button as AntBtn, Form, InputNumber, Radio, Upload } from 'antd'
import { useContext, useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../../components/ui/tabs'
import { alertContext } from '../../contexts/alertContext'
import { subUploadLibFile } from '../../controllers/API'
import MiGuFileList from './MiGuFileList'
import './style.less'

const { Dragger } = Upload

export default function UploadModal({
  id,
  accept,
  open,
  desc = '',
  setOpen,
  onResult,
  MaxFileSize = 50,
  filelibType = ''
}) {
  const [title, setTitle] = useState('上传文件')
  const { t } = useTranslation()
  const [form] = Form.useForm()

  const initValues = {
    chunck_size: 100,
    separator: '\n',
    time_interval: 0,
    deep_analysis: false
  }

  const { fileLibBuriedEvent } = useBuriedEvent()

  // 只有在保存过程中进行校验
  const loadingRef = useRef(false)
  const validateFileList = (_, value, _callback) => {
    if (loadingRef.current && !filePathsRef.current.length) {
      const onlineFiles = kFileList.filter(item => item.id)
      if (onlineFiles.length || selectedOnlineFile.current.length) {
        return Promise.resolve()
      }
      return Promise.reject(t('code.selectFileToUpload'))
    } else {
      return Promise.resolve()
    }
  }

  const validateSplitLen = (_, value, callback) => {
    if (!value) {
      // eslint-disable-next-line prefer-promise-reject-errors
      return Promise.reject('按长度分片不能为空')
    } else if (value < 50) {
      // eslint-disable-next-line prefer-promise-reject-errors
      return Promise.reject('按长度分片最小 50 个字符')
    } else if (value && value > 500) {
      // eslint-disable-next-line prefer-promise-reject-errors
      return Promise.reject('按长度分片最大 500 个字符')
    } else {
      return Promise.resolve()
    }
  }

  const kTimeSplitOptions = [
    {
      value: 0,
      label: t('lib.null')
    },
    {
      value: 1,
      label: `1${t('lib.minute')}`
    },
    {
      value: 5,
      label: `5${t('lib.minute')}`
    },
    {
      value: 30,
      label: `30${t('lib.minute')}`
    }
  ]

  const kPicSplitOptions = [
    {
      value: false,
      label: '否'
    },
    {
      value: true,
      label: '是'
    }
  ]

  const kSelfSplitOptions = [
    // {
    //   value: '',
    //   label: t('lib.null')
    // },
    {
      value: '\n',
      label: t('lib.lineBreaks')
    },
    {
      value: '\n\n',
      label: t('lib.blankRows')
    }
  ]

  const setSubmitObjVal = (obj, key, val) => {
    if (val) {
      obj[key] = val
    }
  }
  /**
   * form end
   */

  const { setErrorData } = useContext(alertContext)

  const chunkType = useRef('chunk')
  const [progressList, setProgressList] = useState([])
  const progressCountRef = useRef(0)

  useEffect(() => {
    if (!open) {
      setProgressList([])
      progressCountRef.current = 0
      filePathsRef.current = []
      failFilesRef.current = []
      chunkType.current = 'chunk'
      if (form) {
        form.setFieldsValue(initValues)
      }
    }
  }, [open])

  const failFilesRef = useRef([]) // 记录上传失败的文件

  // 确定上传文件
  const filePathsRef = useRef([])
  const [loading, setLoading] = useState(false)
  const handleSubmit = () => {
    loadingRef.current = true
    const localSubmitFilesList = filePathsRef.current
      .filter(item => item)
      .map(item => {
        return {
          file_source: 'local',
          url: item
        }
      })
    const miguSubmitFilesList = kFileList
      .filter(item => item.id)
      .map(item => {
        return {
          file_source: 'migu',
          url: item.url,
          name: item.name
        }
      })
    setLoading(true)
    const params: any = {
      // todo 后端结构调整后发布
      // file_path: localSubmitFilesList.concat(miguSubmitFilesList),
      file_path: filePathsRef.current.filter(item => item),
      knowledge_id: Number(id),
      auto: true,
      smart_split: true,
      online_files: miguSubmitFilesList || []
    }

    if (chunkType.current === 'chunk') {
      form
        .validateFields()
        .then(values => {
          console.log('validateFields', values)
          params.auto = false
          params.smart_split = false
          params.deep_analysis = values.deep_analysis
          setSubmitObjVal(params, 'chunck_size', values.chunck_size)
          setSubmitObjVal(params, 'time_interval', values.time_interval)
          values.separator ? (params.separator = values.separator.split(';')) : (params.separator = [])
          submitFileInfo(params)
        })
        .catch(err => {
          console.log('err', err)
          loadingRef.current = false
          setLoading(false)
        })
    } else {
      submitFileInfo(params)
    }
  }
  const submitFileInfo = params => {
    // sub api
    subUploadLibFile(params)
      .then(res => {
        fileLibBuriedEvent({
          page: '上传文件弹窗',
          event_name: '【确定】上传按钮',
          data_id: params.knowledge_id,
          detail: JSON.stringify({
            结果: '成功',
            类型: params.smart_split ? '智能语义切分' : '手动设置切分类型',
            图片深度解析: params.deep_analysis ? '是' : '否',
            时间日志: params.time_interval ? params.time_interval + '分钟' : '无',
            本地上传文件数: params.file_path.length,
            百应云空间上传文件数: params.online_files.length
          })
        })
        setOpen(false)
        onResult?.(progressList.length, failFilesRef.current, res)
      })
      .finally(() => {
        loadingRef.current = false
        setLoading(false)
      })
      .catch(err => {
        console.log(err)
        fileLibBuriedEvent({
          page: '上传文件弹窗',
          event_name: '【确定】上传按钮',
          data_id: params.knowledge_id,
          detail: JSON.stringify({
            结果: '失败',
            类型: params.smart_split ? '智能语义切分' : '手动设置切分类型',
            图片深度解析: params.deep_analysis ? '是' : '否',
            时间日志: params.time_interval ? params.time_interval + '分钟' : '无',
            本地上传文件数: params.file_path.length,
            百应云空间上传文件数: params.online_files.length
          })
        })
      })
  }

  // 上传调度
  const [end, setEnd] = useState(true)

  const upProps: UploadProps = {
    name: 'file',
    multiple: true,
    accept: '.txt, .doc, .docx, .pdf, .xlsx, .csv, .jpg, .jpeg, .png, .json, .md, .log, .ppt, .pptx',
    action: '/api/v1/knowledge/upload',
    headers: {
      'knowledge-id': id
    },
    onChange(info) {
      setEnd(false)
      console.log('fileList Change======》', info.fileList)
      const files = info.fileList.filter(file => file.status === 'uploading')
      if (files.length === 0) {
        filePathsRef.current = info.fileList
          .filter(file => file.status === 'done')
          .map(item => item.response?.data?.file_path)
        setEnd(true)
      }
      const realFiles = info.fileList
        .filter(file => file.status)
        .map(item => {
          if (item.error) {
            item.error.message = 'Upload Failed'
          }
          return item
        })
      setKFileList(realFiles)
      scrollToBottom(realFiles.length)
    },
    beforeUpload: file => {
      let isLt50M = file.size / 1024 / 1024 < MaxFileSize
      // file详情页判断是否为图片格式
      const fileType = file.name.split('.').pop()?.toLowerCase()
      const isImage = ['jpg', 'jpeg', 'png'].includes(fileType)
      if (filelibType && !isImage) {
        MaxFileSize = 50
        isLt50M = file.size / 1024 / 1024 < MaxFileSize
      }
      if (!isLt50M) {
        showMessage({
          content: `${t('code.file')}: ${file.name} 超过${MaxFileSize}M,已移除`,
          type: 'error'
        })
      }
      return isLt50M
    },
    onPreview: () => {},
    progress: {
      strokeColor: {
        '0%': '#108ee9',
        '100%': '#87d068'
      },
      size: {
        height: 2
      },
      format: percent => percent && `${parseFloat(percent.toFixed(2))}%`
    }
  }

  const [kFileList, setKFileList] = useState([])
  useEffect(() => {
    setKFileList([])
  }, [open])

  // 本地文件和云文件------start
  const [uploadType, setUploadType] = useState<'local' | 'migu'>('local')
  const selectedMiGuFileList = useRef([])

  const [openMiGuFileList, setOpenMiGuFileList] = useState<boolean>(false)

  const switchToLocal = () => {
    if (!end) return
    setUploadType('local')
  }

  const switchToMiGu = () => {
    if (!end) return
    setUploadType('migu')
  }
  const handleUploadTabChange = val => {
    if (val === 'migu') {
      switchToMiGu()
    } else {
      switchToLocal()
    }
  }

  // const [onlineFileListContainerHeight, setOnlineFileListContainerHeight] = useState(500)
  const handleMiGuBoxClick = () => {
    console.log('handleMiGuBoxClick')
    setTitle('上传文件>云空间列表')

    // const container = document.querySelector('.file-upload-config-container')
    // if (container) {
    //   // @ts-expect-error  is right，Ignore ts check
    //   setOnlineFileListContainerHeight(container.offsetHeight || 500)
    // }

    setOpenMiGuFileList(true)
  }
  const handleMiGuFileListChange = selectedList => {
    console.log('handleMiGuFileListChange', selectedList)
    selectedMiGuFileList.current = selectedList
  }

  const selectedOnlineFile = useRef([])
  const handleMiGuFileListSubmit = () => {
    console.log('handleMiGuFileListSubmit', selectedMiGuFileList.current)
    const list = selectedMiGuFileList.current.map(item => {
      item.status = 'done'
      return item
    })
    // 文件根据uid去重
    const allFiles = kFileList.concat(list)
    const FilesMap = new Map()
    allFiles.forEach(item => {
      FilesMap.set(item.id ? item.id : item.uid, item)
    })
    console.log('list', list, kFileList.concat(list), Array.from(FilesMap.values()))
    const validList = Array.from(FilesMap.values())
    selectedOnlineFile.current = validList
    setKFileList(validList)
    setOpenMiGuFileList(false)
    scrollToBottom(validList.length)
  }
  // 本地文件和云文件------end

  // 文件列表滚动条保持在底部
  function scrollToBottom(length) {
    const container: any = document.querySelector('.ant-upload-list')
    if (length > 4) {
      container.style.overflow = 'auto'
      container.style.maxHeight = '128px' // 允许内容撑开高度
    } else {
      container.style.overflow = 'hidden'
      container.style.maxHeight = 'auto' // 固定高度
    }
    if (container && container.scrollHeight) {
      requestAnimationFrame(() => {
        container.scrollTop = container.scrollHeight
      })
    }
  }

  return (
    <>
      <ModalComponent
        title={title}
        width={640}
        style={{ top: '10%', minWidth: '640px' }}
        content={
          <div style={{ maxHeight: '64vh' }} className="caseOverFlowY flex  flex-wrap justify-center overflow-y-auto">
            <div
              className="file-upload-config-container w-[600px]"
              style={{ opacity: openMiGuFileList ? '0' : '1', height: openMiGuFileList ? '0' : '100%' }}
            >
              <Form form={form} layout="vertical" initialValues={initValues}>
                {/* <Tabs defaultValue="local" className="w-full pt-[10px]" onValueChange={handleUploadTabChange}>
                  <TabsList>
                    <TabsTrigger value="local" disabled={!end}>
                      本地上传
                    </TabsTrigger>
                    <TabsTrigger value="migu" disabled={!end}>
                      百应云空间
                    </TabsTrigger>
                  </TabsList>
                </Tabs> */}
                <Form.Item>
                  <div
                    className="filelib-online-upload-container cursor-pointer flex-col items-center justify-center gap-[13px]"
                    style={{ display: uploadType === 'migu' ? 'flex' : 'none' }}
                    onClick={handleMiGuBoxClick}
                  >
                    <UploadIcon className="group-hover:text-primary" />
                    <div className="flex flex-col items-center justify-center">
                      <div className="common-upload-main-text">点击上传百应云空间文件</div>
                    </div>
                  </div>
                  <Form.Item name="fileList" validateTrigger="onBlur" rules={[{ validator: validateFileList }]} noStyle>
                    <div
                      className="filelib-upload-file-box-container"
                      style={{ marginTop: uploadType === 'local' ? '20px' : '0' }}
                    >
                      <Dragger
                        {...upProps}
                        className="filelib-upload-file-box"
                        style={{ display: uploadType === 'local' ? 'flex' : 'none' }}
                        fileList={kFileList}
                      >
                        <div className="flex flex-col items-center justify-center gap-[13px] ">
                          <UploadIcon className="group-hover:text-primary" />
                          <div className="flex flex-col items-center justify-center">
                            <div className="common-upload-main-text">{t('lib.clickOrDragHere')}</div>
                            <div className="common-upload-sub-text text-start">{t('lib.supportFileType')}</div>
                            <div className="common-upload-sub-text flex w-[100%] justify-start">
                              注：文件支持UTF-8编码格式
                            </div>
                          </div>
                        </div>
                      </Dragger>
                    </div>
                  </Form.Item>
                </Form.Item>

                <Tabs defaultValue="chunk" className="w-full" onValueChange={val => (chunkType.current = val)}>
                  <TabsList className="">
                    <TabsTrigger value="chunk">{t('code.manualSplit')}</TabsTrigger>
                    {/* <TabsTrigger value="smart" className="roundedrounded-xl">
                      {t('code.smartSplit')}
                    </TabsTrigger> */}
                  </TabsList>
                  <TabsContent value="smart"></TabsContent>
                  <TabsContent value="chunk">
                    <Form.Item
                      name="chunck_size"
                      className="k-create-split-item"
                      labelAlign="left"
                      label={t('lib.lenSplit')}
                      required
                      rules={[{ validator: validateSplitLen }]}
                    >
                      <InputNumber style={{ width: '100%' }} />
                    </Form.Item>

                    <Form.Item
                      name="separator"
                      className="k-create-split-item"
                      labelAlign="left"
                      label={t('lib.selfSplit')}
                    >
                      <Radio.Group>
                        {kSelfSplitOptions.map(({ value, label }) => (
                          <Radio key={value} value={value}>
                            {label}
                          </Radio>
                        ))}
                      </Radio.Group>
                    </Form.Item>

                    <Form.Item label={'图片深度解析'} className="k-create-split-item">
                      <div className="common-text-14-gray mb-[8px]">仅支持.jpg .jepg .png格式的内容深度解析</div>
                      <Form.Item name="deep_analysis" noStyle>
                        <Radio.Group>
                          {kPicSplitOptions.map(({ value, label }) => (
                            <Radio key={label} value={value}>
                              {label}
                            </Radio>
                          ))}
                        </Radio.Group>
                      </Form.Item>
                    </Form.Item>

                    <Form.Item label={t('lib.timeSplit')} className="k-create-split-item">
                      <div className="common-text-14-gray mb-[8px]">仅支持.txt .log格式的时间日志分片</div>

                      <Form.Item name="time_interval" noStyle>
                        <Radio.Group>
                          {kTimeSplitOptions.map(({ value, label }) => (
                            <Radio key={value} value={value}>
                              {label}
                            </Radio>
                          ))}
                        </Radio.Group>
                      </Form.Item>
                    </Form.Item>
                  </TabsContent>
                </Tabs>
              </Form>
            </div>

            {openMiGuFileList && <MiGuFileList height={654} submitMiGuFiles={handleMiGuFileListChange} />}
          </div>
        }
        okText={t('confirmButton')}
        cancelText={t('cancel')}
        onCancel={() => {
          setOpen(false)
        }}
        onOk={() => {
          // submit(checkedValues, checkedLabel)
        }}
        selfFooter={
          openMiGuFileList
            ? [
                <AntBtn
                  key="selfCancel"
                  className="closeBtnStyles h-[34px] w-[92px]"
                  shape="round"
                  onClick={() => {
                    setTitle('上传文件')
                    setOpenMiGuFileList(false)
                  }}
                >
                  上一步
                </AntBtn>,
                <ThemeBtn
                  key="selfConfirm"
                  className="h-[34px] w-[92px]"
                  htmlType="submit"
                  disabled={loading || !end}
                  onClick={handleMiGuFileListSubmit}
                >
                  确定
                </ThemeBtn>
              ]
            : [
                <AntBtn
                  key="selfCancel"
                  className="closeBtnStyles h-[34px] w-[92px]"
                  shape="round"
                  onClick={() => setOpen(false)}
                >
                  {t('cancel')}
                </AntBtn>,
                <ThemeBtn
                  key="selfConfirm"
                  className="h-[34px] w-[92px]"
                  htmlType="submit"
                  disabled={loading || !end}
                  onClick={() => !loading && handleSubmit()}
                >
                  {loading && <span className="loading loading-spinner loading-xs"></span>}
                  {t('confirmButton')}
                </ThemeBtn>
              ]
        }
      />
    </>
  )
}
